package cn.kgc.shiro03.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/28
 * @Description:
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response, HttpSession session){
        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        String code = lineCaptcha.getCode();
        // 存储验证码    redis  key  ->sessionId
        String id = session.getId();
        stringRedisTemplate.opsForValue().set(id,code,1, TimeUnit.MINUTES);

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        lineCaptcha.write(outputStream);

        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
